package top.kaoshanji.p1ch03b;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousChannelGroup;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.Executors;

/**
 * 代码清单 p1ch03b-14：异步套接字通道的使用示例
 * 基于 CompletionHandler 类的实现方式
 * 执行失败...将代码复制进来，还是失败...
 * author kaoshanji
 * ^_^
 * create time 2025/1/11 20:00
 */
public class AsynchronousServerSocketChannelExample01 {

    private static final Logger logger = LogManager.getLogger(AsynchronousServerSocketChannelExample01.class);

    public static void main(String[] args) throws IOException {
        logger.info("...代码清单 p1ch03b-14：异步套接字通道的使用示例...");

        AsynchronousServerSocketChannelExample01 example = new AsynchronousServerSocketChannelExample01();
        example.startAsyncSimpleServer();

    }


    public void startAsyncSimpleServer() throws IOException {
        AsynchronousChannelGroup group = AsynchronousChannelGroup.withFixedThreadPool(10, Executors.defaultThreadFactory());
        final AsynchronousServerSocketChannel serverChannel =
                AsynchronousServerSocketChannel.open(group).bind(new InetSocketAddress(8102));
        serverChannel.accept(null, new CompletionHandler<AsynchronousSocketChannel, Void>() {

            public void completed(AsynchronousSocketChannel clientChannel, Void attachement) {

                serverChannel.accept(null, this);

                try {
                    clientChannel.write(ByteBuffer.wrap("Hello".getBytes(StandardCharsets.UTF_8)));
                    clientChannel.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }

            public void failed(Throwable throwable, Void attachement) {
                throwable.printStackTrace();
            }
        });
    }


}
